<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="7">
        <el-input placeholder="请输入内容" v-model="query.search" class="input-with-select" clearable @clear="getUser">
        <el-button slot="append" icon="el-icon-search" @click="getUser"></el-button>
      </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
      </el-col>
    </el-row>
    <el-table :data="userslist" stripe border>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="手机号" prop="tel"></el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          <span v-if="scope.row.role_id">{{scope.row.role_id.roleName}}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row._id)"></el-button>
          <el-tooltip content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="openRoleDialog(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[2, 3, 4, 5]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
  </el-card>

  <!-- 添加用户对话框 -->
  <el-dialog
    title="添加用户"
    :visible.sync="addDialogVisible"
    width="50%" @close="addDialogClosed">
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
      <el-form-item label="用户名" label-width="80px" prop="username">
        <el-input v-model="addForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" label-width="80px" prop="password">
        <el-input v-model="addForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" label-width="80px" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" label-width="80px" prop="tel">
        <el-input v-model="addForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="生日" label-width="80px" prop="birth">
        <el-date-picker
        v-model="addForm.birth"
        type="date"
        placeholder="选择日期" style="width:100%;">
      </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 修改用户对话框 -->
  <el-dialog
    title="修改用户"
    :visible.sync="editDialogVisible"
    width="50%">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
      <el-form-item label="用户名" label-width="80px">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" label-width="80px" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" label-width="80px" prop="tel">
        <el-input v-model="editForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="生日" label-width="80px" prop="birth">
        <el-date-picker v-model="editForm.birth" type="date" placeholder="选择日期" style="width:100%;"></el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUser">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 分配角色对话框 -->
  <el-dialog
  title="分配角色"
  :visible.sync="getRoleDialogVisib"
  width="50%">
  <el-form :model="roles">
    <el-form-item label="当前用户" label-width="100px">
      <el-input v-model="roles.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="当前角色" label-width="100px">
      <el-input v-model="roles.roleName" disabled></el-input>
    </el-form-item>
    <el-form-item label="选择角色" label-width="100px">
      <el-select v-model="roles.role_id" placeholder="请选择角色">
        <el-option v-for="item in rolelist" :key="item._id" :label="item.roleName" :value="item._id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="getRoleDialogVisib = false">取 消</el-button>
    <el-button type="primary" @click="setRoles">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import {getUsersApi, addUserApi, stateChangeApi, delUserApi, editUserApi, setRolesApi, getRoleAPI} from '../../api/userAPI'
export default {
  created(){
    this.getUser()
  },
  data(){
    // 验证邮箱规则
        var checkEmail = (rule, value, cb) =>{
            // 验证邮箱的正则
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regEmail.test(value)){
                // 合法的邮箱
                return cb()
            }
            cb(new Error('请输入合法的邮箱'))
        }
        // 验证手机号规则
        var checkMobile=(rule, value, cb) =>{
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if(regMobile.test(value)){
                // 合法的邮箱
                return cb()
            }
            cb(new Error('请输入合法的手机号'))
        }
    return{
      // 总条数
      total: 0,
      // 用户列表
      userslist:[],
      // 展示分页搜索参数
      query: {
        page: 1,
        pagesize: 2,
        search: ''
      },
      // 添加表单对话框打开关闭
      addDialogVisible: false,
      // 添加表单
      addForm:{
        username: '',
        password:'',
        email: '',
        tel: '',
        birth: ''
      },
      // 表单验证
      addFormRules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        birth: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
      },
      // 修改表单对话框打开关闭
      editDialogVisible: false,
      // 修改表单
      editForm:{},
      // 修改表单验证
      editFormRules:{
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        birth: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
      },
      // 角色列表
      rolelist: [],
      // 分配角色对话框打开关闭
      getRoleDialogVisib: false,
      // 分配角色时的配置
      roles: {
        // 要分配角色的用户id
        _id: '',
        // 要分配角色的用户名
        username:'',
        // 分配的角色id
        role_id:'',
        // 当前的角色名称
        roleName: ''
      }
    }
  },
  methods:{
    // 展示
    async getUser(){
      let data = await getUsersApi(this.query)
      if (data.status !== 200) return this.$message.error('获取用户列表失败！')
      this.userslist = data.data.data
      this.total = data.data.total
    },
    // 监听每页显示多少条改变事件
    handleSizeChange(newSize){
      this.query.pagesize = newSize
      this.query.page = 1
      this.getUser()
    },
    // 监听页码改变事件
    handleCurrentChange(newPage){
      this.query.page = newPage
      this.getUser()
    },
    // 添加用户对话框关闭事件
    addDialogClosed(){
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser(){
      this.$refs.addFormRef.validate(async valid => {
        if (valid){
          let data = await addUserApi(this.addForm)
          if (data.status !== 200){
            this.addDialogVisible = false
            return this.$message.error('添加用户失败！')
          }
          this.$message.success('添加用户成功！')
          this.getUser()
          this.addDialogVisible = false
        }
      })
    },
    // 更改用户状态
    async stateChange(row){
      let data = await stateChangeApi(row)
      if (data.status !== 200){
        this.$message.error('更新状态失败！')
        return this.getUser()
      }
      this.$message.success('更新状态成功！')
      this.getUser()
    },
    // 删除用户
    async delUser(id){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = await delUserApi(id)
          if (data.status !== 200) return this.$message.error('删除失败！')
          this.$message.success('删除成功！')
          this.getUser()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 修改用户
    // 打开修改用户对话框
    openEditDialog(row){
      this.editForm = {...row}
      this.editDialogVisible = true
    },
    // 修改用户
    editUser(){
      this.$refs.editFormRef.validate(async valid => {
        if (valid){
          let data = await editUserApi(this.editForm)
          if (data.status !== 200){
            this.editDialogVisible = false
            return this.$message.error('修改失败！')
          }
          this.$message.success('修改成功！')
          this.getUser()
          this.editDialogVisible = false
        }
      })
    },
    // 打开分配角色对话框
    async openRoleDialog(row){
      let data = await getRoleAPI()
      // 角色列表赋值
      this.rolelist = data.data
      // 获取要分配角色的用户名
      this.roles.username = row.username
      // 获取要分配角色的用户id
      this.roles._id = row._id
      if (row.role_id){
        // 获取当前角色id和角色名称
        this.roles.role_id = row.role_id._id
        this.roles.roleName = row.role_id.roleName
      }else{
        // 否则就是未分配
        this.roles.role_id = ''
        this.roles.roleName = '未分配'
      }
      this.getRoleDialogVisib = true
    },
    // 分配角色
    async setRoles(){
      let data = await setRolesApi(this.roles)
      if (data.status !== 200){
        this.$message.error('分配角色失败！')
        return this.getRoleDialogVisib = false
      }
      this.$message.success('分配角色成功！')
      this.getUser()
      this.getRoleDialogVisib = false
    }
  }
}
</script>

<style>

</style>